AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")

include("shared.lua")

function ENT:Initialize()
	self.Entity:SetModel("models/Items/item_item_crate.mdl")
	self.Entity:PhysicsInit(SOLID_VPHYSICS)
	self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
	self.Entity:SetSolid(SOLID_VPHYSICS)
	local phys = self.Entity:GetPhysicsObject()
	if phys and phys:IsValid() then phys:Wake() end

	self.Entity:SetUseType(SIMPLE_USE)

	self.Items = {}
	self.HP = 100
end

function ENT:Deposit( name, class, model )
	local Item = { Name = name, Class = class, Model = model }
	table.insert( self.Items, Item )
end

function ENT:Withdraw( ply, class )
	for k, v in pairs( self.Items ) do
		if v.Class == class then
			table.remove(self.Items, k)
			local entity = ents.Create(v.Class)
			entity:SetPos(self:GetPos() + Vector(0,0,30))
			entity:Spawn()
			return
		end
	end
end

function CrateWithdraw(ply, cmd, args)
	Crate = Entity(args[1])
	Crate:Withdraw( ply, args[2] )
end
concommand.Add("RP_CrateWithdraw", CrateWithdraw)

function ENT:Use( activator, caller )
	activator:ChatPrint("Requesting items...")
	local CrateData = { Entity = self.Entity, Items = self.Items }
	datastream.StreamToClients( activator, "CrateItems", CrateData );
end

function ENT:OnTakeDamage(dmg)
	self.Entity:TakePhysicsDamage(dmg)
        self.HP = self.HP - dmg:GetDamage()
        if self.HP <= 0 then
                self.Entity:Destroy()
        end
end

function ENT:Destroy()
	self.Entity:Remove()
end